package com.tech.koufu;

 
import cn.sharesdk.framework.ShareSDK;

import com.igexin.sdk.PushManager;  
import com.tech.koufu.action.StockManager;
import com.tech.koufu.tools.PublicFuc;
import com.tech.koufu.ui.BaseSlideMenuActivity;  
import com.tech.koufu.ui.activity.SearchActivity;
import com.tech.koufu.ui.activity.UserDetailActivity;
import com.tech.koufu.ui.activity.login.LoginActivity;
import com.tech.koufu.ui.activity.login.RegisterActivity;
import com.tech.koufu.ui.activity.menu.MyAttentionActivity; 
import com.tech.koufu.ui.activity.menu.MyCompetitions; 
import com.tech.koufu.ui.activity.menu.MyPositionsActivity;
import com.tech.koufu.ui.activity.menu.MyTrackActivity;
import com.tech.koufu.ui.activity.menu.MyTradeActivity;
import com.tech.koufu.ui.adapter.CustomViewPager;
import com.tech.koufu.ui.adapter.HomePagerAdapter; 
import com.tech.koufu.ui.view.ChooseStockFragment;
import com.tech.koufu.ui.view.CompetitionContentFragment;
import com.tech.koufu.ui.view.HomeContainerFragment;  
import com.tech.koufu.ui.view.MainContentFragment;
import com.tech.koufu.ui.widiget.RotateFreshImageView;
import com.umeng.analytics.MobclickAgent;

import android.content.Context;
import android.content.Intent; 
import android.os.Bundle;   
import android.os.Handler; 
import android.util.Log; 
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;   
import android.widget.ImageView; 
import android.widget.LinearLayout;
import android.widget.RelativeLayout;  
import android.widget.Spinner;
import android.widget.TabHost.OnTabChangeListener; 
import android.widget.TextView; 
import android.widget.Toast;

/**
 * 首页
 * @author jl_luo
 *
 */
public class MainActivity extends BaseSlideMenuActivity implements OnClickListener,OnTabChangeListener{
	private static final String TAG = MainActivity.class.getName();
	private Context mContext;

	public LinearLayout ly_main_pull_title;
	public TextView tv_main_pull_title;

	public Spinner sp_market;
	/**
	 * head 左边头像
	 * 按钮 搜索 刷新 打开右边目录
	 */
	private ImageView icDefHead,btnSearch;
	public RotateFreshImageView btnRefresh;
//	private TabWidget mTabWidget;
	 private long firstBackTime ;
	 private int delay_exit_time = 1500;
	 private Handler handler;
	 private int currentItem ;
	 @Override
	public void onCreate(Bundle savedInstanceState) { 
		super.onCreate(savedInstanceState);
		PushManager.getInstance().initialize(getApplicationContext());
		mContext = this;
		myApp = (MyApplication) getApplication();
		initSlideMenu(); 
		initView();
		StockManager sm = new StockManager(getApplicationContext(),getApplication(),new Handler());
		sm.getNetStocks();  
//		sm.findAllLst();
		MobclickAgent.updateOnlineConfig( mContext ); 
	}

	 @Override
	protected void onResume() { 
		super.onResume();
		ShareSDK.initSDK(this);
		MobclickAgent.onResume(mContext);
	}
	 
	 @Override
	protected void onPause() { 
		super.onPause();
		MobclickAgent.onPause(mContext);
	}
	 
	private void initSlideMenu() { 
		//右侧菜单
		sm.setSecondaryMenu(R.layout.menu_frame_two); 
	}
 

	public void initView() {
		icDefHead = (ImageView)findViewById(R.id.ic_def_head);
		btnSearch = (ImageView)findViewById(R.id.btn_search);
		btnRefresh = (RotateFreshImageView)findViewById(R.id.btn_refresh); 
		icDefHead.setOnClickListener(this);icDefHead.setVisibility(View.VISIBLE);
		btnSearch.setOnClickListener(this);btnSearch.setVisibility(View.VISIBLE); 
		ly_main_pull_title = (LinearLayout)findViewById(R.id.ly_main_pull_title);
		tv_main_pull_title = (TextView)findViewById(R.id.tv_main_pull_title);
		handler = new Handler();
		sp_market = (Spinner)findViewById(R.id.sp_market); 
		initTabs(); 
	}
	private RelativeLayout rl_tab_index,rl_tab_nr,rl_tab_hq,rl_tab_ss;
	private TextView txt_tab_index,txt_tab_nr,txt_tab_hq,txt_tab_ss;
	private View v_tab_index,v_tab_nr,v_tab_hq,v_tab_ss;
	private CustomViewPager vp;
	private HomePagerAdapter homePagerAdapter;
	public void initTabs(){
		vp = (CustomViewPager)findViewById(R.id.vp);
		vp.setOffscreenPageLimit(4);
		vp.setCanScroll(false);
		homePagerAdapter = new HomePagerAdapter(getSupportFragmentManager());
		vp.setAdapter(homePagerAdapter);
		rl_tab_index = (RelativeLayout)findViewById(R.id.rl_tab_index);
		rl_tab_nr = (RelativeLayout)findViewById(R.id.rl_tab_nr);
		rl_tab_hq = (RelativeLayout)findViewById(R.id.rl_tab_hq);
		rl_tab_ss = (RelativeLayout)findViewById(R.id.rl_tab_ss);
		rl_tab_index.setOnClickListener(this);
		rl_tab_nr.setOnClickListener(this);
		rl_tab_hq.setOnClickListener(this);
		rl_tab_ss.setOnClickListener(this);
		txt_tab_index = (TextView)findViewById(R.id.txt_tab_index);
		txt_tab_nr = (TextView)findViewById(R.id.txt_tab_nr);
		txt_tab_hq = (TextView)findViewById(R.id.txt_tab_hq);
		txt_tab_ss = (TextView)findViewById(R.id.txt_tab_ss);
		v_tab_index = (View)findViewById(R.id.v_tab_index);
		v_tab_nr = (View)findViewById(R.id.v_tab_nr);
		v_tab_hq = (View)findViewById(R.id.v_tab_hq);
		v_tab_ss = (View)findViewById(R.id.v_tab_ss);
		//~~~~~~~~~~~~~~~~~ 
	}
	
	@Override
	public void onClick(View v) { 
		switch (v.getId()) {
		case R.id.ic_def_head: 
			 sm.showMenu(true);
			break;
		case R.id.btn_open_right: 
			 sm.showSecondaryMenu(true);
			break;
		case R.id.btn_search:
			Intent intent = new Intent(this,SearchActivity.class);
			startActivity(intent);
			break;
		case R.id.btn_refresh:  
			currentItem = vp.getCurrentItem(); 
			if(currentItem==0){
				HomeContainerFragment hf = (HomeContainerFragment) homePagerAdapter.getItem(currentItem);
				showRefreshRotate();
				hf.refreshContent();
			}else if(currentItem == 3){
				CompetitionContentFragment hf = (CompetitionContentFragment) homePagerAdapter.getItem(currentItem);
				showRefreshRotate();
			}
			break;
		case R.id.iv_big_def_head:
			Toast.makeText(getApplicationContext(), "head pic", Toast.LENGTH_SHORT).show();
			break;
		case R.id.rl_tab_index: 
			if(v_tab_index.getVisibility() != View.VISIBLE){ 
				vp.setCurrentItem(0,false);
				resetTabLine();
				showTabLine(v_tab_index);
				changeTextColor(txt_tab_index, R.color.kfColorRed);
				sp_market.setVisibility(View.GONE);
				if(myApp.isLogin){
					ly_main_pull_title.setVisibility(View.VISIBLE);
					//动态加载数据
					setHomeDateTime(true);
					 
				}
			}
			break;
		case R.id.rl_tab_nr:
			if(v_tab_nr.getVisibility() != View.VISIBLE){ 
				vp.setCurrentItem(1,false);
				resetTabLine();
				showTabLine(v_tab_nr);
				changeTextColor(txt_tab_nr, R.color.kfColorRed);
				btnRefresh.setVisibility(View.GONE);
				ly_main_pull_title.setVisibility(View.GONE);
				sp_market.setVisibility(View.GONE); 
				if(myApp.isLogin){
					setHomeDateTime(false);
				}
			}
			break;
		case R.id.rl_tab_hq:
			if(v_tab_hq.getVisibility() != View.VISIBLE){ 
				vp.setCurrentItem(2,false);
				resetTabLine();
				showTabLine(v_tab_hq);
				changeTextColor(txt_tab_hq, R.color.kfColorRed);
				ly_main_pull_title.setVisibility(View.GONE);
				sp_market.setVisibility(View.VISIBLE);
			}
			break;
		case R.id.rl_tab_ss:
			if(v_tab_ss.getVisibility() != View.VISIBLE){ 
				vp.setCurrentItem(3,false);
				resetTabLine();
				showTabLine(v_tab_ss);
				changeTextColor(txt_tab_ss, R.color.kfColorRed);
				sp_market.setVisibility(View.GONE);
				currentItem = vp.getCurrentItem(); 
				handler.postDelayed(new Runnable() {
					
					@Override
					public void run() {
						CompetitionContentFragment hf = (CompetitionContentFragment) homePagerAdapter.getItem(currentItem);
						hf.mainManualRefresh(0); 
					}
				}, 50);
				
				ly_main_pull_title.setVisibility(View.GONE);
			}
			break;

		default:
			break;
		}
	}
	
	private void setHomeDateTime(boolean isOpen){ 
			HomeContainerFragment hcf = (HomeContainerFragment) homePagerAdapter.getItem(0);
			if(hcf!=null){
				hcf.setMainTime(isOpen);
			} 
	}
	
	/**
	 * 修改bottom tab 样式
	 */
	private MyApplication myApp;


	@Override
	public void onTabChanged(String tabId) {
	
//		mTabHost.setCurrentTabByTag(tabId); 
//		int tab = mTabHost.getCurrentTab();
//		Log.e(TAG, "~~~~~~~tabId="+tabId+">>+tab="); 
//		for(int i=0;i<4; i++){
//			TextView tv = (TextView) mTabWidget.getChildAt(i).findViewById(android.R.id.title);
//			if(i==tab){ 
//				tv.setTextColor(getResources().getColor(R.color.kfColorRed));
//			}else{
//				tv.setTextColor(getResources().getColor(R.color.textColorGray_888888));
//			}
//		} 
		
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) { 
		super.onActivityResult(requestCode, resultCode, data);
		Log.d(TAG, "onActivityResult ,mainActivity requestCode="+requestCode+">resultCode="+resultCode);
		if(requestCode== PublicFuc.CODE_Back && resultCode == PublicFuc.CODE_Back){ 
			HomeContainerFragment homeFragment = (HomeContainerFragment) homePagerAdapter.getItem(0);
			homeFragment.changeFragment();
			showLeftMenu();
		}else if(requestCode == PublicFuc.code_login_suss){
			myApp = (MyApplication) getApplication();
			if(data!=null){
				boolean islogin = data.getBooleanExtra("islogin", false);
//				Log.w(TAG, "is Logi00n...."+islogin);
			}
//			Log.w(TAG, "is Login...."+myApp.isLogin);
			if(myApp.isLogin){
				handler.postDelayed(new Runnable() { 
					@Override
					public void run() { 
						showContent(); 
					}
				}, 50);
			}
		}
	}
	public void showLeftMenu(){
		myApp = (MyApplication) getApplication();
		leftMenuFragment.showLeftMenu(myApp.isLogin);
	}
	public void showContent(){
		HomeContainerFragment homeFragment = (HomeContainerFragment) homePagerAdapter.getItem(0);
		homeFragment.changeContentFragment();
		showLeftMenu();
	}
	public void menuLoginOnclick(final View view){
		sm.showContent(true);
		handler.postDelayed(new Runnable() {

			@Override
			public void run() { 
				switch (view.getId()) {
				case R.id.rl_menu_login:
					Intent intent = new Intent(MainActivity.this,LoginActivity.class);
					 startActivityForResult(intent, PublicFuc.code_login_suss); 
					break;
				case R.id.rl_menu_register:
					 intent = new Intent(MainActivity.this,RegisterActivity.class);
					 startActivityForResult(intent, PublicFuc.code_login_suss); 
					break; 
				default:
					break;
				}
			}
			
		}, 250);
	}
	
	/**
	 * 菜单页 按钮监听
	 * @param view
	 */
	public void menuOnclick(final View view){ 
		try {
			sm.showContent(true);
			handler.postDelayed(new Runnable() {
				
				@Override
				public void run() {
					myApp = (MyApplication) getApplication();
					if(!myApp.isLogin){
//					Intent intent = new Intent(this,LoginActivity.class);   
//					startActivityForResult(intent, 3); 
						Toast.makeText(MainActivity.this, "请先登录", Toast.LENGTH_SHORT).show();
						return;
					} 
					switch (view.getId()) {
					case R.id.rl_menu_myAttention://我的关注
						Intent intent = new Intent(MainActivity.this, MyAttentionActivity.class);
						intent.putExtra("userid", myApp.getDigitalid());
						startActivity(intent);
						break;
					case R.id.rl_menu_myTrack://我的追踪
						intent = new Intent(MainActivity.this, MyTrackActivity.class); 
						intent.putExtra("userid", myApp.getDigitalid());
						startActivity(intent);
						break;
					case R.id.rl_menu_mytransaction: //我的交易
						intent = new Intent(MainActivity.this, MyTradeActivity.class); 
						intent.putExtra("userid", myApp.getUserid());
						intent.putExtra("groupid", myApp.getGroupId());
						intent.putExtra("digitalid", myApp.getDigitalid());
						startActivity(intent);
						break;
					case R.id.rl_menu_my_page: //用户主页
						myApp = (MyApplication) getApplication();
						intent = new Intent(MainActivity.this,UserDetailActivity.class);
						intent.putExtra("userid", myApp.getDigitalid());
						intent.putExtra("username", myApp.getUserName()); 
						startActivity(intent);
						break;
					case R.id.rl_menu_my_stock_position: //我的持仓
						intent = new Intent(MainActivity.this, MyPositionsActivity.class); 
						HomeContainerFragment homeFragment = (HomeContainerFragment) homePagerAdapter.getItem(0); 
						MainContentFragment cfg = homeFragment.getContentFrg();
						intent.putExtra("userStocks", cfg.list);
						intent.putExtra("userid", myApp.getDigitalid());
						intent.putExtra("userName", myApp.getUserName());
						intent.putExtra("userInfo", cfg.info);
						startActivity(intent);
						break; 
					case R.id.rl_menu_myCompetition: //我的大赛
						intent = new Intent(MainActivity.this, MyCompetitions.class); 
						startActivity(intent);
						break;
//					case R.id.rl_menu_myChooseStock:
//						intent = new Intent(MainActivity.this, MyChooseStockActivity.class); 
//						startActivity(intent);
//						break;
					case R.id.menu_kfCompetition://right_menu
						sm.showContent(true);
						rl_tab_ss.performClick();
						break;
					case R.id.menu_stockQuotes:
						sm.showContent(true);
						rl_tab_hq.performClick();
						break;
					case R.id.menu_topranking:
						sm.showContent(true);
						rl_tab_nr.performClick();
						break;
					case R.id.menu_selfStock: 
						homeFragment = (HomeContainerFragment) homePagerAdapter.getItem(0); 
						cfg = homeFragment.getContentFrg();
						intent = new Intent(MainActivity.this,ChooseStockFragment.class); 
						intent.putExtra("userStock",cfg.list);
						startActivity(intent); 
						break; 
					default:
						break;
					} 
				}
			}, 150);
		} catch (Exception e) { 
			e.printStackTrace();
		}
		
		
	}
	
	private void resetTabLine(){ 
		v_tab_index.setVisibility(View.INVISIBLE);
		v_tab_nr.setVisibility(View.INVISIBLE);
		v_tab_hq.setVisibility(View.INVISIBLE);
		v_tab_ss.setVisibility(View.INVISIBLE);
		
		txt_tab_index.setTextColor(getResources().getColor(R.color.textColorGray_888888));
		txt_tab_nr.setTextColor(getResources().getColor(R.color.textColorGray_888888));
		txt_tab_hq.setTextColor(getResources().getColor(R.color.textColorGray_888888));
		txt_tab_ss.setTextColor(getResources().getColor(R.color.textColorGray_888888));
	}
	private void showTabLine(View v){
		v.setVisibility(View.VISIBLE);
	}
	private void changeTextColor(TextView tv,int colors){
		tv.setTextColor(getResources().getColor(colors));
	}
	private void showRefreshRotate(){
		btnRefresh.startRotate(R.drawable.image_progress);
	}
	public void cancleRefreshRotate(){
		btnRefresh.cancelRotete(R.drawable.btn_refresh);
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) { 
		if(keyCode == KeyEvent.KEYCODE_BACK){ 
			long secondTime = System.currentTimeMillis(); 
            if (secondTime - firstBackTime > delay_exit_time) {//如果两次按键时间间隔大于800毫秒，则不退出 
                Toast.makeText(MainActivity.this, R.string.app_exit_toast_msg, 
                        Toast.LENGTH_SHORT).show(); 
                firstBackTime = secondTime;//更新firstTime 
                return false; 
            } else {  
            	finish(); 
    			System.exit(0);//否则退出程序 
            }  
		} 
		return super.onKeyDown(keyCode, event);
	}
	@Override
	protected void onDestroy() { 
		super.onDestroy();
		HomeContainerFragment hcf = (HomeContainerFragment) homePagerAdapter.getItem(0);
		if(hcf!=null){
			hcf.cleadMainThread();;
		} 
	}

}
